<template>
  <div class="service_person_container">
    <div class="body">
      <!-- 按钮组 & 搜索条件 -->
      <div class="header">
        <div class="btn_group">
          <HPlainButton v-permission="'empList_add'" @click="addEmp">新增工程师</HPlainButton>
          <HPlainButton v-permission="'empList_import'" @click="inImportExcel">导入工程师</HPlainButton>
        </div>

        <!-- 搜索条件 -->
        <div class="search">
          <!-- 日期范围 -->
          <DateRange ref="dateRangeRef" @change="handleDateChange" />
          <el-input
            v-model.trim="search.userSearch"
            clearable
            placeholder="部门名称/服务人员名称/手机号"
            class="keyword_input"
            @keyup.enter="requestEmpListApi"
            @clear="requestEmpListApi"
          />
          <HButton type="primary" @click="requestEmpListApi">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </HButton>
          <HButton @click="clearValue">
            <el-icon>
              <RefreshRight />
            </el-icon>
            重置
          </HButton>
        </div>
      </div>
      <!-- 表单内容 -->
      <div class="table">
        <el-table
          v-loading="loading"
          :border="true"
          :data="empList"
          element-loading-text="加载中..."
          height="100%"
          row-key="id"
        >
          <template #empty>
            <el-empty description="暂无数据" />
          </template>

          <!-- 序号 -->
          <el-table-column label="序号" type="index" width="50" :align="'center'" fixed="left" />

          <!-- 姓名 -->
          <el-table-column show-overflow-tooltip label="姓名" prop="userName" min-width="220" />

          <!-- 手机号 -->
          <el-table-column show-overflow-tooltip label="手机号" prop="userPhone" width="108" />

          <!-- 接单策略 -->
          <el-table-column label="接单策略" prop="autoSureReceiveOrder" width="98">
            <template #default="item">
              <span>{{ item.row.autoSureReceiveOrder ? '自动确认接单' : '手动确认接单' }}</span>
            </template>
          </el-table-column>

          <!-- 所属部门 -->
          <el-table-column show-overflow-tooltip label="所属部门" prop="network" min-width="300" />

          <!-- 技能   saas/格美淇隐藏-->

          <!-- <el-table-column
            show-overflow-tooltip
            prop="networkEmpSkill"
            label="技能"
            min-width="120"
          /> -->

          <!-- 等级 -->
          <el-table-column show-overflow-tooltip prop="networkEmpLevel" label="等级" width="50" />

          <!-- 创建时间 -->
          <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="128" />

          <!-- 更新时间 -->
          <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="128" />

          <!-- 在职状态 -->
          <el-table-column prop="quit" label="在职状态" width="74" fixed="right" :align="'center'">
            <template #default="scope">
              <HStatus v-if="scope.row.quit" type="info">离职</HStatus>
              <HStatus v-else>在职</HStatus>
            </template>
          </el-table-column>

          <!-- 操作 -->
          <el-table-column fixed="right" label="操作" width="90">
            <template #default="scope">
              <h-space>
                <HLink v-permission="'empList_update'" @click="editDialogShow(false, scope.row)">详细</HLink>
                <h-link v-permission="'empList_delete'" type="error" @click="handleDelServicePerson(scope.row)">删除</h-link>
              </h-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <Pagination
          ref="pagination"
          :list_total="total"
          @size-change="requestEmpListApi()"
          @current-change="requestEmpListApi(false)"
        />
      </div>
    </div>
    <SelfDefined
      v-model="addDialog"
      :is-add="show"
      :get-row="getRow"
      @update-list="requestEmpListApi"
    />
  </div>
</template>

<script setup lang="ts" name="emp">
  import { ref, onMounted } from 'vue'
  import { Action, ElMessage, ElMessageBox, MessageBoxState } from 'element-plus'
  import Pagination from '@/components/Pagination/index.vue'
  import { deleteNetworkEmp, getEmpList } from '@/api/network'
  import SelfDefined from '../../emp/components/SelfDefined.vue'
  import { useRouter } from 'vue-router'
  import DateRange from '@/components/DateRange.vue'
  import { Search, RefreshRight } from '@element-plus/icons-vue'
  import { ServicePerson } from './types'
  import routeComponentName from '@/config/route-component-name'

  defineOptions({
    name: routeComponentName.network.networkEmpList,
  })

  const handleDelServicePerson = (servicePerson: ServicePerson) => {
    ElMessageBox.confirm(`是否删除部门工程师: ${servicePerson.userName}`, '提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'error',
      autofocus: false,
      beforeClose(action: Action, instance: MessageBoxState, done: () => void) {
        if (action === 'cancel' || action === 'close') {
          done()
        }

        if (action === 'confirm') {
          instance.cancelButtonLoading = true
          instance.confirmButtonLoading = true
          deleteNetworkEmp(servicePerson.empRealtionId).then((res) => {
            if (res.data.success) {
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: 'success',
                duration: 5000,
                plain: true,
              })
              done()
              requestEmpListApi()
            } else {
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: 'error',
                duration: 5000,
                plain: true,
              })
            }
            instance.cancelButtonLoading = false
            instance.confirmButtonLoading = false
          })
        }
      },
    })
  }

  const router = useRouter()

  // 动画加载
  const loading = ref(false)

  // 服务人员列表总数量
  const total = ref(0)

  // 服务人员列表
  const empList = ref([])

  // 开始日期
  const startDate = ref('')

  // 结束日期
  const endDate = ref('')
  const pagination = ref()
  // 开始日期是否大于结束日期
  const isStartDateGreaterThanEndDate = ref(false)

  // 服务人员搜索对象
  const search = ref({
    page: 1,
    limit: 50,
    userSearch: '', // 部门名称/服务人员名称/手机号
    startTime: '', // 创建开始时间
    endTime: '', // 创建结束时间
  })
  const addDialog = ref(false)
  const show = ref(null)

  // 日期更新事件
  const handleDateChange = (param: {
    startDate: string
    endDate: string
    isStartDateGreaterThanEndDate: boolean
  }) => {
    if (param.isStartDateGreaterThanEndDate) {
      ElMessage({
        type: 'error',
        message: '开始日期不能大于结束日期',
        duration: 5000,
        showClose: true,
        plain: true,
      })
      return false
    }
    startDate.value = param.startDate
    endDate.value = param.endDate
    isStartDateGreaterThanEndDate.value = param.isStartDateGreaterThanEndDate
    requestEmpListApi()
  }

  // 获取服务人员列表
  const requestEmpListApi = (val = true) => {
    if (val) {
      pagination.value.setPage()
    }
    if (isStartDateGreaterThanEndDate.value) {
      ElMessage({
        type: 'error',
        message: '开始日期不能大于结束日期',
        duration: 5000,
        showClose: true,
        plain: true,
      })
      return
    }
    search.value.startTime = startDate.value ? startDate.value : ''
    search.value.endTime = endDate.value ? endDate.value : ''
    ;(search.value.page = pagination.value.current), //当面页码
      (search.value.limit = pagination.value.size), //每页显示数量
      (loading.value = true)
    getEmpList(search.value).then((res) => {
      loading.value = false
      if (!res.data.success) {
        ElMessage.error(res.data.message)
      }
      total.value = Number(res.data?.data.total)
      empList.value = res.data?.data.rows
    })
  }

  // DateRange组件实例
  const dateRangeRef = ref<InstanceType<typeof DateRange> | null>(null)

  // 清空搜索条件
  const clearValue = () => {
    startDate.value = ''
    endDate.value = ''
    if (dateRangeRef.value) {
      dateRangeRef.value.resetDateRange()
    }
    isStartDateGreaterThanEndDate.value = false
    search.value.userSearch = ''
    requestEmpListApi()
  }

  // 新增工程师
  const addEmp = () => {
    addDialog.value = true
    show.value = true
  }

  // 添加or修改员工信息
  const getRow = ref(null)
  function editDialogShow(add: boolean, row: any = null) {
    addDialog.value = true
    show.value = add
    getRow.value = row
  }

  const inImportExcel = () => {
    router.push({ path: 'empExcelImport' })
  }

  onMounted(() => {
    requestEmpListApi()
  })
</script>

<style scoped lang="scss">
  @import './index.scss';
</style>
